# -*- coding: utf-8 -*-
# @Time   : 2024-05-13 09:43
# @Author : 大龙 🚀

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from utils.tools import urlencode


class HnCsscsswcqrmzf537APolicy(BaseTaxPolicySpider):
    name = 'hn_csscsswcqrmzf_537a_policy'

    province = "湖南省"
    city = "长沙市"
    county = "望城区"
    park = ""
    source = "长沙市望城区人民政府"

    def start_requests(self):
        page_url = 'http://www.wangcheng.gov.cn/xxgk_343/qzfxxgkml/fggw_352/gfxwjsjk/gdwxt/index.html'
        url = "http://search.changsha.gov.cn/igs/front/search/list.html"
        params = {
            "index": "wenjianku",
            "type": "wenjian",
            "siteId": "17",
            "filter[DOCTITLE,DOCCONTENT,FILENUM-or]": "",
            "filter[_SITEID]": "178",
            "filter[SUBCATID_1]": "",
            "filter[DOCCHANNEL]": "63109,63112,63129",
            "filter[FILETYPE]": "",
            "orderProperty": "DOCRELTIME",
            "orderDirection": "desc",
            "pageNumber": "1",
            "pageSize": "13"
        }
        yield scrapy.Request(url + '?' + urlencode(params), callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for info in response.json()['page']['content']:
            item = Item()
            item['source_url'] = info['DOCPUBURL']
            item['publish_date'] = info['SIGNDATE'] if 'SIGNDATE' in info else info['DOCRELTIME']
            if 'T' in item['publish_date']:
                item['publish_date'] = item['publish_date'].split('T')[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.json()['page']['totalPages']
            for page_num in range(2, int(total_page) + 1):
                url = response.url.replace('pageNumber=1', f'pageNumber={page_num}')
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline
    cmdline.execute("scrapy crawl hn_csscsswcqrmzf_537a_policy".split())
